// src/main/java/org/example/backend/controller/CompanyEvaluationController.java
package org.example.backend.controller;

import jakarta.validation.Valid;
import org.example.backend.dto.EvaluationDto;
import org.example.backend.dto.PageResponseDto;
import org.example.backend.entity.*;
import org.example.backend.exception.BusinessException;
import org.example.backend.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/company")
@CrossOrigin
@PreAuthorize("hasRole('COMPANY')")
public class CompanyEvaluationController {

    private static final Logger logger = LoggerFactory.getLogger(CompanyEvaluationController.class);

    private final CompanyService companyService;
    private final UserService userService;
    private final EvaluationService evaluationService;
    private final InternshipService internshipService;

    public CompanyEvaluationController(CompanyService companyService, UserService userService,
                                     EvaluationService evaluationService, InternshipService internshipService) {
        this.companyService = companyService;
        this.userService = userService;
        this.evaluationService = evaluationService;
        this.internshipService = internshipService;
    }

    /**
     * 企业提交学生成绩评定
     */
    @PostMapping("/evaluations")
    public ResponseEntity<?> evaluateStudent(@Valid @RequestBody EvaluationDto evaluationDto) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            Company company = companyService.getCompanyByUserId(currentUser.getId());

            // 添加调试信息
            boolean isCompanyInternship = internshipService.isCompanyInternship(evaluationDto.getInternshipId(), company.getId());
            logger.info("企业评定权限检查 - 实习ID: {}, 企业ID: {}, 是否为企业实习: {}",
                    evaluationDto.getInternshipId(), company.getId(), isCompanyInternship);

            // 验证是否有权限评定该学生
            if (!isCompanyInternship) {
                logger.warn("企业无权限评定该学生 - 实习ID: {}, 企业ID: {}", evaluationDto.getInternshipId(), company.getId());
                throw new BusinessException("无权限对该学生进行评定");
            }

            // 创建评定记录
            Evaluation evaluation = evaluationService.createEvaluation(evaluationDto, company.getId(), 2); // 2表示企业评定

            Map<String, Object> response = new HashMap<>();
            response.put("message", "成绩评定成功");
            response.put("evaluation", evaluation);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("成绩评定失败", e);
            return ResponseEntity.badRequest().body("评定失败：" + e.getMessage());
        }
    }


    /**
     * 获取企业的历史评定记录
     */
    @GetMapping("/evaluations")
    public ResponseEntity<?> getCompanyEvaluations(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            Company company = companyService.getCompanyByUserId(currentUser.getId());

            Page<Evaluation> evaluations = evaluationService.getEvaluationsByEvaluator(company.getId(), 2, page, size);
            PageResponseDto<Evaluation> response = new PageResponseDto<>(
                    evaluations.getContent(),
                    evaluations.getNumber(),
                    evaluations.getSize(),
                    (int) evaluations.getTotalElements(),
                    evaluations.getTotalPages()
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取评定记录失败", e);
            return ResponseEntity.badRequest().body("获取评定记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取特定实习的评定记录
     */
    @GetMapping("/internships/{internshipId}/evaluations")
    public ResponseEntity<?> getInternshipEvaluations(@PathVariable Long internshipId) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);
            Company company = companyService.getCompanyByUserId(currentUser.getId());

            // 验证是否有权限查看该实习的评定记录
            if (internshipService.isCompanyInternship(internshipId, company.getId())) {
                throw new BusinessException("无权限查看该实习的评定记录");
            }

            // 获取该实习的所有评定记录
            Iterable<Evaluation> evaluations = evaluationService.getEvaluationsByInternship(internshipId);

            Map<String, Object> response = new HashMap<>();
            response.put("evaluations", evaluations);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("获取实习评定记录失败", e);
            return ResponseEntity.badRequest().body("获取评定记录失败：" + e.getMessage());
        }
    }
}
